﻿using AutoMapper;
using ManagementApi.Models;
using ManagementApi.Models.System.Dept;
using ManagementApi.Mvc.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules.System.Area;
using Modules.System.Dept;
using PmSoft;
using PmSoft.Utilities;

namespace ManagementApi.Controllers.SystemManage
{
    /// <summary>
    /// 主管单位相关业务接口
    /// </summary>
    [Route("/api/v1/depts")]
    [ApiController]
    [Authorize(Roles = "SysUser")]
    public class DeptController : ControllerBase
    {
        private readonly DeptService deptService;
        private readonly AreaService areaService;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="deptService"></param>
        /// <param name="mapper"></param>
        public DeptController(
            DeptService deptService,
             IMapper mapper,
             AreaService areaService
            )
        {
            this.deptService = deptService;
            this.mapper = mapper;
            this.areaService = areaService;
        }

        /// <summary>
        /// 获取单位列表(分页)
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns></returns>
        [HttpGet("page")]
        public ApiResult<PageDto<DeptDto>> GetDepts([FromQuery] DeptQuery query, int pageNum = 1, int pageSize = 20)
        {
            var depts = deptService.GetDepts(query, pageNum, pageSize);
            var dtos = depts.AsPageDto(source => { return source.AsDeptDto(); });
            return ApiResult<PageDto<DeptDto>>.Success(dtos);
        }

        /// <summary>
        /// 部门下拉
        /// </summary>
        /// <returns></returns>
        [HttpGet("options")]
        public ApiResult<IEnumerable<VueTree<int>>> GetDeptOptions()
        {
            var trees = deptService.GetAllDepts().AsTrees();
            return ApiResult<IEnumerable<VueTree<int>>>.Success(trees);
        }

        /// <summary>
        /// 主管单位表单数据
        /// </summary>
        /// <param name="id">主管单位ID</param>
        /// <returns></returns>
        [HttpGet("{id}/form")]
        public ApiResult<DeptEditForm> GetDept(int id)
        {
            var menu = deptService.GetSysDept(id);
            if (menu == null)
                return ApiResult<DeptEditForm>.Failure("主管单位数据不存在");
            DeptEditForm deptEditForm = new DeptEditForm();
            mapper.Map(menu, deptEditForm);
            if (!deptEditForm.AreaCode.HasValue || deptEditForm.AreaCode == 0)
            {
                if (!deptEditForm.CityCode.HasValue || deptEditForm.CityCode == 0)
                    deptEditForm.AreaId = deptEditForm.ProvinceCode;
                else
                    deptEditForm.AreaId = deptEditForm.CityCode;
            }
            else
                deptEditForm.AreaId = deptEditForm.AreaCode;
            return ApiResult<DeptEditForm>.Success(deptEditForm);
        }

        /// <summary>
        /// 创建主管单位
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost("create")]
        [PermissionCheck("sys:dept:add")]
        public ApiResult Add(DeptEditForm form)
        {
            SysDept dept = new SysDept();
            mapper.Map(form, dept);
            var areaCodes = areaService.GetAreaTuple(form.AreaId.Value);
            dept.ProvinceCode = areaCodes.ProvinceCode;
            dept.CityCode = areaCodes.CityCode;
            dept.AreaCode = areaCodes.AreaCode;
            dept.CreateTime = DateTime.Now;
            if (form.Level == (int)AdministrativeLevel.Area)
            {
                if (dept.AreaCode == null || dept.AreaCode == 0)
                    return ApiResult.Failure("所属地区必须是归属区县");
            }
            else if (form.Level == (int)AdministrativeLevel.City)
            {
                if (dept.CityCode == null || dept.CityCode == 0)
                    return ApiResult.Failure("所属地区必须是归属地市");
            }
            else
            {
                if (dept.ProvinceCode == null || dept.ProvinceCode == 0)
                    return ApiResult.Failure("所属省必须选择");
            }

            deptService.CreateDept(dept);
            return ApiResult.Success("创建成功");
        }

        /// <summary>
        /// 修改主管单位
        /// </summary>
        /// <param name="id"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        [PermissionCheck("sys:dept:edit")]
        public ApiResult Update(int id, DeptEditForm form)
        {
            var dept = deptService.GetSysDept(id);
            if (dept == null) return ApiResult.Failure("主管单位不存在");
            mapper.Map(form, dept);
            dept.DeptId = id;
            var areaCodes = areaService.GetAreaTuple(form.AreaId.Value);
            dept.ProvinceCode = areaCodes.ProvinceCode;
            dept.CityCode = areaCodes.CityCode;
            dept.AreaCode = areaCodes.AreaCode;
            dept.CreateTime = DateTime.Now;
            if (form.Level == (int)AdministrativeLevel.Area)
            {
                if (dept.AreaCode == null || dept.AreaCode == 0)
                    return ApiResult.Failure("所属地区必须是归属区县");
            }
            else if (form.Level == (int)AdministrativeLevel.City)
            {
                if (dept.CityCode == null || dept.CityCode == 0)
                    return ApiResult.Failure("所属地区必须是归属地市");
            }
            else
            {
                if (dept.ProvinceCode == null || dept.ProvinceCode == 0)
                    return ApiResult.Failure("所属省必须选择");
            }
            deptService.UpdateDept(dept);
            return ApiResult.Success("编辑成功");
        }

        /// <summary>
        /// 删除主管单位
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{ids}")]
        [PermissionCheck("sys:dept:delete")]
        public ApiResult Delete(string ids)
        {
            deptService.DeleteDepts(ValueUtility.ConvertToList<int>(ids));
            return ApiResult.Success("删除成功");
        }
    }
}